var event = require('event.js');
function upload(options) {
  var url = options.url,
    path = options.path,
    name = options.name,
    extra = options.extra,
    success = options.success,
    progress = options.progress,
    size = options.size,
    uploadType = options.uploadType,
    fail = options.fail
    
  const uploadTask = wx.uploadFile({
    url: url,
    filePath: path,
    name: name,
    formData: extra,
    success: function(res) {
      var data = res.data
      try {
        data = JSON.parse(res.data)
      } catch (e) {
        console.log(e)
        throw (e)
      }

      if (res.statusCode == 200) {
        if (success) {
          success(data)
        }
      } else {
        console.log('错误')
        console.log(res)
        if (fail) {
          console.log(fail)
          fail(data)
        }
      }

    },
    fail: function(res) {    
      if (fail) {
        fail(res)
      }
    }
  })

  uploadTask.onProgressUpdate((res) => {
    event.emit('UploadChanged',res)
    // if (progress >= 0)(     
    //   wx.showLoading({
    //     title: '已经上传' + res.progress + '%',
    //     mask: true
    //   })
    // )
  })
}

module.exports = {
  upload: upload
}